package is.server.controller.session.remote;

import is.common.datatype.Request;
import is.common.interfaces.Command;
import is.common.interfaces.DeactivationNeededThread;
import is.common.util.ObjectStreamer;

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;

/**
 * Provides user sessions interface. One thread per user. May use local and remote adaptors
 *
 * @author aspr0
 *         Date: 01.04.12
 *         Time: 6:17
 */
public class RemoteSessionThread extends Thread implements DeactivationNeededThread
{
    private Socket socket;
    private boolean sessionActive = true;
    ObjectOutputStream objectOutputStream;
    ObjectInputStream objectInputStream;
    ObjectStreamer objectStreamer;

    public RemoteSessionThread(Socket socket) throws IOException
    {
        this.socket = socket;
        objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
        objectInputStream = new ObjectInputStream(socket.getInputStream());
        objectStreamer = new ObjectStreamer(objectInputStream, objectOutputStream);
    }

    public void deactivate()
    {
        sessionActive = false;
        try
        {
            objectInputStream.close();
            objectOutputStream.close();
            socket.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public void run()
    {
        while (sessionActive)
        {
            try
            {
                Request request = objectStreamer.receiveRequest();
                Command command = CommandFactory.newInstance(request, objectStreamer);
                command.execute();
            }
            catch (EOFException e)
            {
//                e.printStackTrace();
                deactivate();
            }
            catch (SocketException e)
            {
//                e.printStackTrace();
                deactivate();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            catch (ClassNotFoundException e)
            {
                e.printStackTrace();
            }
        }

        try
        {
            socket.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
